<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="故障编号" prop="faultTypeCode">
        <el-input v-model="queryParams.faultTypeCode" placeholder="请输入故障编号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="故障名称" prop="faultTypeName">
        <el-input v-model="queryParams.faultTypeName" placeholder="请输入故障名称" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['devices:fault-type:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['devices:fault-type:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['devices:fault-type:delete']"
        >
          批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table
      ref="table"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
      @expand-change="handleExpandChange"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table
            v-loading="props.row.loading"
            :data="props.row.children || []"
            size="small"
            border
            :show-overflow-tooltip="true"
            style="width: 95%;margin:0 auto"
            header-row-class-name="custom-header-row"
          >
            <el-table-column prop="faultTypeCode" label="故障编号" align="center"/>
            <el-table-column prop="faultTypeName" label="故障名称" align="center"/>
            <el-table-column label="状态" align="center" prop="status">
              <template v-slot="scope">
                <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" >
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120">
              <template v-slot="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                           v-hasPermi="['devices:fault-type:update']">修改
                </el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                           v-hasPermi="['devices:fault-type:delete']">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="故障编号" align="center" prop="faultTypeCode"/>
      <el-table-column label="故障名称" align="center" prop="faultTypeName"/>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                     v-hasPermi="['devices:fault-type:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['devices:fault-type:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <FaultTypeForm ref="formRef" @success="getList"/>
  </div>
</template>

<script>
import * as FaultTypeApi from '@/api/devices/faulttype/index.js';
import FaultTypeForm from './FaultTypeForm.vue';
import {getDictDatas, getDictDataLabel, DICT_TYPE} from '@/utils/dict'

export default {
  name: "FaultType",
  components: {
    FaultTypeForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 故障类型列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        faultTypeCode: null,
        faultTypeName: null,
        parentId: 0, // 默认查询parentId为0的根节点
        status: null,
        createTime: [],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      this.list = []
      try {
        this.loading = true;
        // 查询根节点列表（parentId=0）
        const res = await FaultTypeApi.getFaultTypePage({...this.queryParams, parentId: 0});
        const rootList = res.data.list;
        this.total = res.data.total;

        // 初始设置每个根节点可能有子节点，显示展开箭头
        rootList.forEach(node => {
          node.hasChildren = true;
          node.children = null; // 初始时不加载子节点
          // 添加一个随机标识，确保每次数据更新都会触发重新渲染
          node._uid = Math.random().toString(36).substr(2, 9);
        });

        this.list = rootList;
      } catch {
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      // 强制更新数据，触发表格重新渲染
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.parentId = 0; // 重置为查询根节点
      // 强制更新数据，触发表格重新渲染
      this.getList();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除故障类型编号为"' + id + '"的数据项?')
      try {
        await FaultTypeApi.deleteFaultType(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除故障类型 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await FaultTypeApi.deleteFaultTypeList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有故障类型数据项?');
      try {
        this.exportLoading = true;
        this.$download.excel(data, '故障类型.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
    async handleExpandChange(row, expanded) {
      if (expanded && row.hasChildren && !row.children) {
        // 如果展开且没有加载过子节点，则加载子节点
        row.loading = true;
        try {
          const childRes = await FaultTypeApi.getFaultTypePage({pageSize: 100, parentId: row.id});
          if (childRes.data.list && childRes.data.list.length > 0) {
            row.children = childRes.data.list;
            // 为子节点也设置可能有子节点
            row.children.forEach(child => {
              child.hasChildren = true;
              child.children = null;
            });
          } else {
            row.children = [];
            row.hasChildren = false; // 没有子节点，不再显示展开箭头
          }
        } catch {
        } finally {
          row.loading = false;
        }
      }
    },
  }
};
</script>

<style>
/* 使用深度选择器确保样式能正确应用到子表格表头 */
::v-deep .custom-header-row th {
  background-color: #659cdb !important;
  color: white;
}

/* 确保表头单元格也应用样式 */
::v-deep .custom-header-row .cell {
  color: white;
}
</style>
